package com.group.flagtivities;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.text.TextUtils;
import android.util.Base64;
import android.view.Gravity;
import android.view.Surface;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.group.flagtivities.CustomMapView.OnLongPressListener;

public class Flagtivities extends MapActivity implements OnClickListener, OnLongPressListener {
	
	private static CustomMapView mapView;
	private static ImageView settings;
	private static ImageView filter;
	private static ImageView permission;
	private static ImageView friend;
	private static ImageView search;
	private static ImageView recentSortRecent;
	private static ImageView recentSortLike;
	private static ImageView recentSortAttending;
	
	private static final int PUBLIC = 0;
	public static final int REQUEST = 0;
	public static final int FRIENDS = 1;
	public static final int PENDING = 2;
	private static int hLat = 42646877;
	private static int hLon = -87856047;
	private static int filter_id = 0;
	private static int recentSort_id = 0;
	private static int permission_id = 0;
	
	public static int user_id;
	public static String name;
	
	private static boolean landscape;
	
	private static CustomItemizedOverlay mapAthletics;
	private static CustomItemizedOverlay mapComputerScience;
	private static CustomItemizedOverlay mapFineArts;
	private static CustomItemizedOverlay mapForeignLanguage;
	private static CustomItemizedOverlay mapHumanities;
	private static CustomItemizedOverlay mapMathematics;
	private static CustomItemizedOverlay mapSocial;
	private static CustomItemizedOverlay mapAthleticsPrivate;
	private static CustomItemizedOverlay mapComputerSciencePrivate;
	private static CustomItemizedOverlay mapFineArtsPrivate;
	private static CustomItemizedOverlay mapForeignLanguagePrivate;
	private static CustomItemizedOverlay mapHumanitiesPrivate;
	private static CustomItemizedOverlay mapMathematicsPrivate;
	private static CustomItemizedOverlay mapSocialPrivate;
	
	public static ArrayList<FlagtivityObject> FlagtivityList;
	public static ArrayList<FriendObject> FriendList;
	public static ArrayList<FriendObject> FriendRequestList;
	public static ArrayList<FriendObject> FriendPendingList;
	
	public static MapController mapController;
	private static List<Overlay> mapOverlay;
	private static Context mContext;
	
	private Messenger messengerOut = null;
	private Messenger friendsOut = null;
	private final Messenger messengerIn = new Messenger(new IncomingActivitiesHandler());
	private final Messenger friendsIn = new Messenger(new IncomingFriendsHandler());
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        findViews();
        clearLists();
        configure();
        configureOrientation();
        if (landscape) configureLandscape();
        configureMap();
                
        TextUtil.setFont((ViewGroup) findViewById(R.id.main), getAssets());
    }
	
	private void clearLists() {
		FriendList = new ArrayList<FriendObject>();
		FriendRequestList = new ArrayList<FriendObject>();
		FriendPendingList = new ArrayList<FriendObject>();
	}
	
	private void clearOverlays() {
		Drawable athleticsFlag = ImageUtil.colorFlag(getResources().getDrawable(R.drawable.flag), getResources().getColor(R.color.red_light), getResources().getColor(R.color.red_dark));
		Drawable computerScienceFlag = ImageUtil.colorFlag(getResources().getDrawable(R.drawable.flag), getResources().getColor(R.color.orange_light), getResources().getColor(R.color.orange_dark));
		Drawable fineArtsFlag = ImageUtil.colorFlag(getResources().getDrawable(R.drawable.flag), getResources().getColor(R.color.yellow_light), getResources().getColor(R.color.yellow_dark));
		Drawable foreignLanguageFlag = ImageUtil.colorFlag(getResources().getDrawable(R.drawable.flag), getResources().getColor(R.color.green_light), getResources().getColor(R.color.green_dark));
		Drawable humanitiesFlag = ImageUtil.colorFlag(getResources().getDrawable(R.drawable.flag), getResources().getColor(R.color.blue_light), getResources().getColor(R.color.blue_dark));
		Drawable mathematicsFlag = ImageUtil.colorFlag(getResources().getDrawable(R.drawable.flag), getResources().getColor(R.color.indigo_light), getResources().getColor(R.color.indigo_dark));
		Drawable socialFlag = ImageUtil.colorFlag(getResources().getDrawable(R.drawable.flag), getResources().getColor(R.color.violet_light), getResources().getColor(R.color.violet_dark));
		
		mapAthletics = new CustomItemizedOverlay(new BitmapDrawable(((BitmapDrawable) athleticsFlag).getBitmap()), mContext);
		mapComputerScience = new CustomItemizedOverlay(new BitmapDrawable(((BitmapDrawable) computerScienceFlag).getBitmap()), mContext);
		mapFineArts = new CustomItemizedOverlay(new BitmapDrawable(((BitmapDrawable) fineArtsFlag).getBitmap()), mContext);
		mapForeignLanguage = new CustomItemizedOverlay(new BitmapDrawable(((BitmapDrawable) foreignLanguageFlag).getBitmap()), mContext);
		mapHumanities = new CustomItemizedOverlay(new BitmapDrawable(((BitmapDrawable) humanitiesFlag).getBitmap()), mContext);
		mapMathematics = new CustomItemizedOverlay(new BitmapDrawable(((BitmapDrawable) mathematicsFlag).getBitmap()), mContext);
		mapSocial = new CustomItemizedOverlay(new BitmapDrawable(((BitmapDrawable) socialFlag).getBitmap()), mContext);
		
		mapAthleticsPrivate = new CustomItemizedOverlay(new BitmapDrawable(((BitmapDrawable) athleticsFlag).getBitmap()), mContext);
		mapComputerSciencePrivate = new CustomItemizedOverlay(new BitmapDrawable(((BitmapDrawable) computerScienceFlag).getBitmap()), mContext);
		mapFineArtsPrivate = new CustomItemizedOverlay(new BitmapDrawable(((BitmapDrawable) fineArtsFlag).getBitmap()), mContext);
		mapForeignLanguagePrivate = new CustomItemizedOverlay(new BitmapDrawable(((BitmapDrawable) foreignLanguageFlag).getBitmap()), mContext);
		mapHumanitiesPrivate = new CustomItemizedOverlay(new BitmapDrawable(((BitmapDrawable) humanitiesFlag).getBitmap()), mContext);
		mapMathematicsPrivate = new CustomItemizedOverlay(new BitmapDrawable(((BitmapDrawable) mathematicsFlag).getBitmap()), mContext);
		mapSocialPrivate = new CustomItemizedOverlay(new BitmapDrawable(((BitmapDrawable) socialFlag).getBitmap()), mContext);
	}
	
	private void mapOverlays() {
		if (mapAthletics.size() > 0 && (filter_id == 0 || filter_id == 1)) mapOverlay.add(mapAthletics);
		if (mapComputerScience.size() > 0 && (filter_id == 0 || filter_id == 2))mapOverlay.add(mapComputerScience);
		if (mapFineArts.size() > 0 && (filter_id == 0 || filter_id == 3))mapOverlay.add(mapFineArts);
		if (mapForeignLanguage.size() > 0 && (filter_id == 0 || filter_id == 4))mapOverlay.add(mapForeignLanguage);
		if (mapHumanities.size() > 0 && (filter_id == 0 || filter_id == 5))mapOverlay.add(mapHumanities);
		if (mapMathematics.size() > 0 && (filter_id == 0 || filter_id == 6))mapOverlay.add(mapMathematics);
		if (mapSocial.size() > 0 && (filter_id == 0 || filter_id == 7))mapOverlay.add(mapSocial);
		
		if (mapAthleticsPrivate.size() > 0 && (filter_id == 0 || filter_id == 1)) mapOverlay.add(mapAthleticsPrivate);
		if (mapComputerSciencePrivate.size() > 0 && (filter_id == 0 || filter_id == 2))mapOverlay.add(mapComputerSciencePrivate);
		if (mapFineArtsPrivate.size() > 0 && (filter_id == 0 || filter_id == 3))mapOverlay.add(mapFineArtsPrivate);
		if (mapForeignLanguagePrivate.size() > 0 && (filter_id == 0 || filter_id == 4))mapOverlay.add(mapForeignLanguagePrivate);
		if (mapHumanitiesPrivate.size() > 0 && (filter_id == 0 || filter_id == 5))mapOverlay.add(mapHumanitiesPrivate);
		if (mapMathematicsPrivate.size() > 0 && (filter_id == 0 || filter_id == 6))mapOverlay.add(mapMathematicsPrivate);
		if (mapSocialPrivate.size() > 0 && (filter_id == 0 || filter_id == 7))mapOverlay.add(mapSocialPrivate);
	}
	
	class IncomingFriendsHandler extends Handler {
		@Override
		public void handleMessage(Message msg) {			
			clearLists();
			handleFriends(msg.getData().getString("friends"));
		}
	}
	
	private void handleFriends(String friends) {
		try {
			JSONArray jFriends = new JSONArray(friends);
			for (int i = 0; i < jFriends.length(); i++) {
				JSONObject jFriend = jFriends.getJSONObject(i);
				int friend_id = Integer.parseInt(jFriend.getString("FRIEND_ID"));
				String first = jFriend.getString("FIRST");
				String last = jFriend.getString("LAST");
				int status = Integer.parseInt(jFriend.getString("STATUS"));
				FriendObject friend = new FriendObject(friend_id, first, last, status);
				
				switch(friend.status) {
				case 0:
					FriendRequestList.add(friend);
					break;
				case 1:
					FriendList.add(friend);
					break;
				case 2:
					FriendPendingList.add(friend);
				}
			}
			
			try{
				Message msg = Message.obtain(null, ActivityService.REQUEST_ACTIVITIES);
				msg.replyTo = messengerIn;
				messengerOut.send(msg);
			}catch (Exception e) {}
			
		}catch(Exception e) {}
	}
	
	class IncomingActivitiesHandler extends Handler {
		@Override
		public void handleMessage(Message msg) {
			String activities = msg.getData().getString("activities");
			FlagtivityList = new ArrayList<FlagtivityObject>();
			if (activities != null && !activities.equalsIgnoreCase("")) {
				mapOverlay.clear();
				clearOverlays();
				handleActivities(activities);
				mapOverlays();
				mapView.invalidate();
				if (landscape) populateRecents();
			}else {
				if (landscape) clearRecents();
				mapOverlay.clear();
				mapView.invalidate();
				clearOverlays();
			}
		}
	}
	
	private ServiceConnection connection = new ServiceConnection() {
		@Override
		public void onServiceConnected(ComponentName className, IBinder service) {
			messengerOut = new Messenger(service);
			try{
				Message msg = Message.obtain(null, ActivityService.REGISTER_CLIENT);
				msg.replyTo = messengerIn;
				messengerOut.send(msg);
			}catch(Exception e) {}
		}

		@Override
		public void onServiceDisconnected(ComponentName name) {
			messengerOut = null;
		}
	};
	
	private ServiceConnection fConnection = new ServiceConnection() {
		@Override
		public void onServiceConnected(ComponentName className, IBinder service) {
			friendsOut = new Messenger(service);
			try{
				Message msg = Message.obtain(null, FriendService.REGISTER_CLIENT);
				msg.replyTo = friendsIn;
				friendsOut.send(msg);
			}catch(Exception e) {}
		}

		@Override
		public void onServiceDisconnected(ComponentName name) {
			friendsOut = null;
		}
	};
	
	private void configureOrientation() {
		int orientation = getWindowManager().getDefaultDisplay().getRotation();
        if (orientation == Surface.ROTATION_90 || orientation == Surface.ROTATION_90) {
        	hLat = 42646266;
        	hLon = -87856076;
        	landscape = true;
        }else {
        	hLat = 42646877;
        	hLon = -87856047;
        	landscape = false;
        }
	}
	
	private void findViews() {
		settings = (ImageView) findViewById(R.id.settings);
        permission = (ImageView) findViewById(R.id.permission);
        filter = (ImageView) findViewById(R.id.filter);
        search = (ImageView) findViewById(R.id.search);
        friend = (ImageView) findViewById(R.id.friend);
        recentSortRecent = (ImageView) findViewById(R.id.recentSortRecent);
        recentSortLike = (ImageView) findViewById(R.id.recentSortLike);
        recentSortAttending = (ImageView) findViewById(R.id.recentSortAttending);
        mapView = (CustomMapView) findViewById(R.id.mapView);
	}
	
	private void configure() {
		user_id = getIntent().getIntExtra("user_id", 0);
		name = getIntent().getStringExtra("name");
		
		mContext = this;
		
		mapView.setOnLongPressListener(this);
        mapView.setBuiltInZoomControls(true);
        mapView.setSatellite(true);
        settings.setOnClickListener(this);
        permission.setOnClickListener(this);
        filter.setOnClickListener(this);
        search.setOnClickListener(this);
        friend.setOnClickListener(this);
	}
	
	private void configureLandscape() {
		recentSortRecent.setOnClickListener(this);
        recentSortLike.setOnClickListener(this);
        recentSortAttending.setOnClickListener(this);
	}
	
	private void configureMap() {
		mapController = mapView.getController();
        mapController.setCenter(new GeoPoint(hLat, hLon));
        mapController.setZoom(18);
        mapOverlay = mapView.getOverlays();
	}
    
    private void filter() {
    	mapOverlay.clear();
    	if (mapAthletics.size() > 0 && (filter_id == 0 || filter_id == 1) && (permission_id == 0 || permission_id == 1)) mapOverlay.add(mapAthletics);
		if (mapComputerScience.size() > 0 && (filter_id == 0 || filter_id == 2) && (permission_id == 0 || permission_id == 1))mapOverlay.add(mapComputerScience);
		if (mapFineArts.size() > 0 && (filter_id == 0 || filter_id == 3) && (permission_id == 0 || permission_id == 1))mapOverlay.add(mapFineArts);
		if (mapForeignLanguage.size() > 0 && (filter_id == 0 || filter_id == 4) && (permission_id == 0 || permission_id == 1))mapOverlay.add(mapForeignLanguage);
		if (mapHumanities.size() > 0 && (filter_id == 0 || filter_id == 5) && (permission_id == 0 || permission_id == 1))mapOverlay.add(mapHumanities);
		if (mapMathematics.size() > 0 && (filter_id == 0 || filter_id == 6) && (permission_id == 0 || permission_id == 1))mapOverlay.add(mapMathematics);
		if (mapSocial.size() > 0 && (filter_id == 0 || filter_id == 7) && (permission_id == 0 || permission_id == 1))mapOverlay.add(mapSocial);
		if (mapAthleticsPrivate.size() > 0 && (filter_id == 0 || filter_id == 1) && (permission_id == 0 || permission_id == 2)) mapOverlay.add(mapAthleticsPrivate);
		if (mapComputerSciencePrivate.size() > 0 && (filter_id == 0 || filter_id == 2) && (permission_id == 0 || permission_id == 2))mapOverlay.add(mapComputerSciencePrivate);
		if (mapFineArtsPrivate.size() > 0 && (filter_id == 0 || filter_id == 3) && (permission_id == 0 || permission_id == 2))mapOverlay.add(mapFineArtsPrivate);
		if (mapForeignLanguagePrivate.size() > 0 && (filter_id == 0 || filter_id == 4) && (permission_id == 0 || permission_id == 2))mapOverlay.add(mapForeignLanguagePrivate);
		if (mapHumanitiesPrivate.size() > 0 && (filter_id == 0 || filter_id == 5) && (permission_id == 0 || permission_id == 2))mapOverlay.add(mapHumanitiesPrivate);
		if (mapMathematicsPrivate.size() > 0 && (filter_id == 0 || filter_id == 6) && (permission_id == 0 || permission_id == 2))mapOverlay.add(mapMathematicsPrivate);
		if (mapSocialPrivate.size() > 0 && (filter_id == 0 || filter_id == 7) && (permission_id == 0 || permission_id == 2))mapOverlay.add(mapSocialPrivate);
		mapView.invalidate();
    }
    
    private void logout() {
    	SharedPreferences settings = getSharedPreferences("flagtivitiesPrefs", MODE_PRIVATE);
    	SharedPreferences.Editor editor = settings.edit();
    	
    	editor.putInt("user_id", 0);
    	editor.putString("name", null);
    	editor.commit();
    	
		startActivity(new Intent(this, Welcome.class));
		finish();
    }
    
	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}
	
	private boolean isContained(ArrayList<FriendObject> friends, int owner) {
		for (FriendObject friend : friends) {
			if (friend.friend_id == owner) return true;
		}
		
		return false;
	}
	
	private void handleActivities(String activities) {
		if (landscape) clearRecents();
		
		try{
			JSONArray jActivities = new JSONArray(activities);
			for (int i = 0; i < jActivities.length(); i++) {
				boolean addActivity = true;
				JSONObject jActivity = jActivities.getJSONObject(i);
				int permission = Integer.parseInt(jActivity.getString("PERMISSION"));
				String type = jActivity.getString("TYPE");
				int activity_id = Integer.valueOf(jActivity.getString("ACTIVITY_ID"));
				String owner = jActivity.getString("OWNER");
				int lat = Integer.valueOf(jActivity.getString("LAT"));
				int lon = Integer.valueOf(jActivity.getString("LON"));
				String description = jActivity.getString("DESCRIPTION");
				String room = jActivity.getString("ROOM");
				String title = jActivity.getString("TITLE");
				String start = jActivity.getString("START");
				String end = jActivity.getString("END");
				String dislikes = jActivity.getString("DISLIKES");
				String likes = jActivity.getString("LIKES");
				String attending = jActivity.getString("ATTENDING");
				
				CustomOverlayItem iActivity = new CustomOverlayItem(new GeoPoint(lat, lon), null, null, type, owner, title, description, room, start, end, dislikes, likes, attending, activity_id);
				
				switch(Integer.parseInt(type)) {
				case TypePicker.ATHLETICS:
					if (permission == PUBLIC) mapAthletics.addOverlay(iActivity);
					else if (Integer.parseInt(owner) == user_id || isContained(FriendList, Integer.parseInt(owner))) mapAthleticsPrivate.addOverlay(iActivity);
					else addActivity = false;
					break;
				case TypePicker.COMPUTER_SCIENCE:
					if (permission == PUBLIC) mapComputerScience.addOverlay(iActivity);
					else if (Integer.parseInt(owner) == user_id || isContained(FriendList, Integer.parseInt(owner))) mapComputerSciencePrivate.addOverlay(iActivity);
					else addActivity = false;
					break;
				case TypePicker.FINE_ARTS:
					if (permission == PUBLIC) mapFineArts.addOverlay(iActivity);
					else if (Integer.parseInt(owner) == user_id || isContained(FriendList, Integer.parseInt(owner))) mapFineArtsPrivate.addOverlay(iActivity);
					else addActivity = false;
					break;
				case TypePicker.FOREIGN_LANGUAGE:
					if (permission == PUBLIC) mapForeignLanguage.addOverlay(iActivity);
					else if (Integer.parseInt(owner) == user_id || isContained(FriendList, Integer.parseInt(owner))) mapForeignLanguagePrivate.addOverlay(iActivity);
					else addActivity = false;
					break;
				case TypePicker.HUMANITIES:
					if (permission == PUBLIC) mapHumanities.addOverlay(iActivity);
					else if (Integer.parseInt(owner) == user_id || isContained(FriendList, Integer.parseInt(owner))) mapHumanitiesPrivate.addOverlay(iActivity);
					else addActivity = false;
					break;
				case TypePicker.MATHEMATICS:
					if (permission == PUBLIC) mapMathematics.addOverlay(iActivity);
					else if (Integer.parseInt(owner) == user_id || isContained(FriendList, Integer.parseInt(owner))) mapMathematicsPrivate.addOverlay(iActivity);
					else addActivity = false;
					break;
				case TypePicker.SOCIAL:
					if (permission == PUBLIC) mapSocial.addOverlay(iActivity);
					else if (Integer.parseInt(owner) == user_id || isContained(FriendList, Integer.parseInt(owner))) mapSocialPrivate.addOverlay(iActivity);
					else addActivity = false;
					break;
				}
				
				if (addActivity) FlagtivityList.add(new FlagtivityObject(activity_id, permission, Integer.parseInt(owner), Long.parseLong(jActivity.getString("CREATED")), Integer.parseInt(type), title, room, description, lat, lon, Integer.parseInt(likes), Integer.parseInt(dislikes), Integer.parseInt(attending), start, end));
			}
		}catch (Exception e) {}
	}
	
	private void clearRecents() {
		LinearLayout recent = (LinearLayout) findViewById(R.id.recent);
		RelativeLayout recentSort = (RelativeLayout) findViewById(R.id.recentSort);
		recent.removeAllViews();
		recent.addView(recentSort);
	}
	
	private void sortByRecent() {
		Comparator<FlagtivityObject> comparator = new Comparator<FlagtivityObject>() {
			public int compare(FlagtivityObject a, FlagtivityObject b) {
				Long aC = new Long(a.creation);
				Long bC = new Long(b.creation);

				if (aC < bC) return 1;
				else if (aC > bC) return -1;
				else return 0;
			}
		};
		
		Collections.sort(FlagtivityList, comparator);
	}
	
	private void sortByLike() {
		Comparator<FlagtivityObject> comparator = new Comparator<FlagtivityObject>() {
			public int compare(FlagtivityObject a, FlagtivityObject b) {
				Integer aL = new Integer(a.like);
				Integer bL = new Integer(b.like);

				if (aL < bL) return 1;
				else if (aL > bL) return -1;
				else return 0;
			}
		};
		
		Collections.sort(FlagtivityList, comparator);
	}
	
	private void sortByAttending() {
		Comparator<FlagtivityObject> comparator = new Comparator<FlagtivityObject>() {
			public int compare(FlagtivityObject a, FlagtivityObject b) {
				Integer aA = new Integer(a.attending);
				Integer bA = new Integer(b.attending);

				if (aA < bA) return 1;
				else if (aA > bA) return -1;
				else return 0;
			}
		};
		
		Collections.sort(FlagtivityList, comparator);
	}
	
	private void configureFlag(TextView view, int type) {
		Drawable drawable = null;
		
		switch(type) {
		case 1:
			drawable = ImageUtil.colorSwatch(40, 40, getResources().getColor(R.color.red_light), getResources().getColor(R.color.red_dark));
			break;
		case 2:
			drawable = ImageUtil.colorSwatch(40, 40, getResources().getColor(R.color.orange_light), getResources().getColor(R.color.orange_dark));
			break;
		case 3:
			drawable = ImageUtil.colorSwatch(40, 40, getResources().getColor(R.color.yellow_light), getResources().getColor(R.color.yellow_dark));
			break;
		case 4:
			drawable = ImageUtil.colorSwatch(40, 40, getResources().getColor(R.color.green_light), getResources().getColor(R.color.green_dark));
			break;
		case 5:
			drawable = ImageUtil.colorSwatch(40, 40, getResources().getColor(R.color.blue_light), getResources().getColor(R.color.blue_dark));
			break;
		case 6:
			drawable = ImageUtil.colorSwatch(40, 40, getResources().getColor(R.color.indigo_light), getResources().getColor(R.color.indigo_dark));
			break;
		case 7:
			drawable = ImageUtil.colorSwatch(40, 40, getResources().getColor(R.color.violet_light), getResources().getColor(R.color.violet_dark));
			break;
		}
        
		if (drawable != null) {
			drawable.setBounds(0, 0, 40, 40);
			view.setCompoundDrawablesWithIntrinsicBounds(drawable, null, null, null);
        	view.setCompoundDrawablePadding(10);
		}
	}
	
	private void populateRecents() {
		clearRecents();
		
		switch(recentSort_id) {
		case 0:
			sortByRecent();
			break;
		case 1:
			sortByLike();
			break;
		case 2:
			sortByAttending();
			break;
		}
		
		RelativeLayout recentSort = (RelativeLayout) findViewById(R.id.recentSort);
		LinearLayout recent = (LinearLayout) findViewById(R.id.recent);
		int height = (mapView.getHeight() - recentSort.getHeight()) / 10;
		
		int recentCount = 0;
		for (int i = 0; i < FlagtivityList.size() && recentCount < 10; i++) {
			FlagtivityObject flag = FlagtivityList.get(i);
			if ((filter_id == 0 || filter_id == flag.type) && (permission_id == 0 || permission_id == flag.permission + 1)) {
				TextView v = new TextView(this);
				v.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, height));
				v.setSingleLine(true);
				v.setText(flag.title);
				v.setTypeface(Typeface.createFromAsset(getAssets(), "fonts/Chunkfive.otf"), Typeface.NORMAL);
				v.setPadding(10, 0, 10, 0);
				v.setTextColor(getResources().getColor(R.color.white));
				v.setShadowLayer(1.0f, 0.0f, 0.0f, getResources().getColor(R.color.gray_dark));
				v.setBackgroundDrawable(getResources().getDrawable(R.drawable.background_recent));
				v.setGravity(Gravity.CENTER_VERTICAL);
				v.setEllipsize(TextUtils.TruncateAt.END);
				final int lat = flag.lat;
				final int lon = flag.lon;
				v.setOnClickListener(new OnClickListener() {
					public void onClick(View view) {
						mapController.setCenter(new GeoPoint(lat, lon));
					}
				});
				
				configureFlag(v, flag.type);
				
				recent.addView(v);
				recentCount++;
			}
		}
	}

	@Override
	public void onLongPress(MapView view, GeoPoint longPressLocation) {
		Bundle b = new Bundle();
		b.putInt("Lat", longPressLocation.getLatitudeE6());
		b.putInt("Lon", longPressLocation.getLongitudeE6());
		Intent intent = new Intent(this, Create.class);
		intent.putExtra("Location", b);
		startActivity(intent);
	}
	
	@Override
	public void onStart() {
		super.onStart();
		
		bindService(new Intent(this, ActivityService.class), connection, Context.BIND_AUTO_CREATE);
		bindService(new Intent(this, FriendService.class), fConnection, Context.BIND_AUTO_CREATE);
	}
	
	@Override
	public void onStop() {
		super.onStop();
		
		unbindService(connection);
		unbindService(fConnection);
	}
	
	@Override
	public void onResume() {
		super.onResume();
		
		try{
			Message msg = Message.obtain(null, ActivityService.REQUEST_ACTIVITIES);
			msg.replyTo = messengerIn;
			messengerOut.send(msg);
		}catch(Exception e) {}
		
		try{
			Message msg = Message.obtain(null, FriendService.REQUEST_FRIENDS);
			msg.replyTo = friendsIn;
			friendsOut.send(msg);
		}catch(Exception e) {}
	}

	private void setFilterDrawable() {
		switch (filter_id) {
    	case 0:
    		filter.setBackgroundColor(getResources().getColor(R.color.white));
    		break;
    	case 1:
    		filter.setBackgroundColor(getResources().getColor(R.color.red_light));
    		break;
    	case 2:
    		filter.setBackgroundColor(getResources().getColor(R.color.orange_light));
    		break;
    	case 3:
    		filter.setBackgroundColor(getResources().getColor(R.color.yellow_light));
    		break;
    	case 4:
    		filter.setBackgroundColor(getResources().getColor(R.color.green_light));
    		break;
    	case 5:
    		filter.setBackgroundColor(getResources().getColor(R.color.blue_light));
    		break;
    	case 6:
    		filter.setBackgroundColor(getResources().getColor(R.color.indigo_light));
    		break;
    	case 7:
    		filter.setBackgroundColor(getResources().getColor(R.color.violet_light));
    		break;
    	}
	}
	
	private void setProfilePicture(Uri localImage) {
		try {
			Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(localImage));
			ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
			bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
			byte[] byteArray = outputStream.toByteArray();
			String byteString = Base64.encodeToString(byteArray, Base64.DEFAULT);
			WebUtil.setProfilePicture(byteString, user_id);
		}catch(Exception e) {}
	}
	
	@Override
	public void onClick(View v) {
		switch(v.getId()) {
		case R.id.button:
			mapController.animateTo(new GeoPoint(hLat, hLon));
			break;
		case R.id.settings:
			startActivityForResult(new Intent(this, Settings.class), 0);
			overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
			break;
		case R.id.filter:
			filter_id++;
	    	if (filter_id > 7) filter_id = 0;
	    	setFilterDrawable();
			filter();
			if (landscape) populateRecents();
			break;
		case R.id.permission:
			permission_id++;
			if (permission_id > 2) permission_id = 0;
			if (permission_id == 0) permission.setImageDrawable(getResources().getDrawable(R.drawable.flag));
			else if (permission_id == 1) permission.setImageDrawable(getResources().getDrawable(R.drawable.public_white));
			else if (permission_id == 2) permission.setImageDrawable(getResources().getDrawable(R.drawable.private_white));
			filter();
			if (landscape) populateRecents();
			break;
		case R.id.recentSortRecent:
			recentSort_id = 0;
			populateRecents();
			break;
		case R.id.recentSortLike:
			recentSort_id = 1;
			populateRecents();
			break;
		case R.id.recentSortAttending:
			recentSort_id = 2;
			populateRecents();
			break;
		case R.id.search:
			startActivity(new Intent(this, Search.class));
			break;
		case R.id.friend:
			startActivity(new Intent(this, Friend.class));
			break;
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == 0) {
			switch(resultCode) {
			case Settings.RESULT_LOGOUT:
				logout();
				break;
			case Settings.RESULT_PROFILE_PICTURE:
				Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
				startActivityForResult(intent, 1);
				break;
			}
		}else if (requestCode == 1 && resultCode == RESULT_OK) {
			setProfilePicture(data.getData());
		}
		super.onActivityResult(requestCode, resultCode, data);
	}
	
}